
import { createRouter, createWebHistory } from 'vue-router'
import {ElMessage} from 'element-plus'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'default',
      // 重定向到登录页面
      redirect: '/login'
    },
    {
      path:"/home",
      name:"home",
      component:()=>import("../views/Home/HomeView.vue")
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login/LoginView.vue')
    },
    // 用户注册页面
    {
      path: '/register',
      name:'register',
      component: () => import('../views/Login/RegisterView.vue')
    },
    // 修改密码页面
    {
      path:'/edit/:id',
      name:'edit',
      component:()=>import('../views/Login/EditView.vue')
    },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('../views/NotFound/NotFoundView.vue')
    }
  ]
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 登录页面直接放行
  if (to.name === 'login' || to.name ==='register') {
    next()
  } else {
    // 其他页面需要登录验证
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      ElMessage.error('请先登录')
      next({ name: 'login' })
    }
  }
})

export default router
